import 'dart:io';
import 'dart:ui';

import 'package:bot_toast/bot_toast.dart';
import 'package:moonplay/common/common_height.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:moonplay/common/app_common.dart';
import 'package:moonplay/pages/tabbar/four_page.dart';
import 'package:moonplay/pages/tabbar/one_page.dart';
import 'package:moonplay/pages/tabbar/three_page.dart';
import 'package:moonplay/pages/tabbar/two_page.dart';
import 'package:moonplay/utils/loading.dart';
import 'package:moonplay/widgets/custom_top_widget.dart';
// import 'package:jpush_flutter/jpush_flutter.dart';

class AppIndexPage extends StatefulWidget {
  @override
  _AppIndexPageState createState() => _AppIndexPageState();
}

class _AppIndexPageState extends State<AppIndexPage> {
  DateTime lastPopTime;

  int _selectedIndex = 0;
  static const _noColor = 0xff888888;
  static const _selectColor = 0xffffffff;
  static const _textFontSize = 11.0;
  static const _iconSize = 17.0;

  var _footerText = [
      {"text": "首页","icon": 0xe634},
      // {"text": "频道","icon": 0xe63c},
      // {"text": "消息","icon": 0xe63a},
      {"text": "我的","icon": 0xe63d},
    ];
  

  final _bottomSheetKey = GlobalKey<ScaffoldState>();
  // JPush jpush = new JPush();

  void _onItemTapped(int index) {
    if (_selectedIndex == index) {
      print('点击的tab相同');
    }
    setState(() {
      _selectedIndex = index;
    });
  }

  List<Widget> _bottomNavPages = List(); // 底部导航栏各个可切换页面组

  bool enableSlideOff = true;
  bool onlyOne = true;
  bool crossPage = true;
  int seconds = 3;
  int animationMilliseconds = 200;
  int animationReverseMilliseconds = 200;
  BackButtonBehavior backButtonBehavior = BackButtonBehavior.none;

  @override
  void initState() {
    super.initState();

    getAppPackageInfo();

    initJpushState();
    _bottomNavPages
      ..add(OnePage())
      // ..add(TwoPage());
      // ..add(ThreePage())
      ..add(FourPage());

    
  }

  @override
  void dispose() {
    super.dispose();
    //取消订阅
  }

  Future<void> initJpushState() async {
    // jpush.getRegistrationID().then((rid) {
    //   //在极光中注册的ID， 将来可以传到后台，后台根据ID来进行推送
    //   print('---->rid:${rid}');
    // });

    // jpush.setup(
    //   appKey: "83953fcfe1b3ba97c7b8813d",
    //   channel: "developer-default", //暂时填写默认值即可
    //   production: false, //设置是开发环境还是生产环境
    //   debug: true, //debug模式
    // );

    // //推送设置
    // if (Platform.isIOS) {
    //   jpush.applyPushAuthority(
    //       new NotificationSettingsIOS(sound: true, alert: true, badge: true));
    // }

    // try {
    //   /*监听响应方法的编写*/
    //   jpush.addEventHandler(
    //     /**
    //      * 接收到通知，在状态栏显示，并且这里也有提示
    //      */
    //     onReceiveNotification: (Map<String, dynamic> message) async {
    //       print(">>>>>>>>>>>>>>>>>flutter 接收到推送: $message");
    //       showNewWidget();
    //     },

    //     /**
    //      * 点击通知
    //      */
    //     onOpenNotification: (Map<String, dynamic> message) async {
    //       //根据返回的信息处理点击事件
    //       _openJpushDetail(message);
    //       print("点击通知: $message");
    //     },

    //     /**
    //      * 接收到自定义的消息，此消息不会在状态栏出现
    //      */
    //     onReceiveMessage: (Map<String, dynamic> message) async {
    //       print("flutter onReceiveMessage: $message");
    //     },
    //   );
    // } on PlatformException {}

    // if (!mounted) {
    //   return;
    // }
  }

  _openJpushDetail(message) {
    // Navigator.push(
    //   context,
    //   new MaterialPageRoute(
    //     builder: (context) => TestJpushPage(message: message),
    //   ),
    // );
  }

  showNewWidget() {
    BotToast.showCustomNotification(
        animationDuration: Duration(milliseconds: animationMilliseconds),
        animationReverseDuration:
            Duration(milliseconds: animationReverseMilliseconds),
        //如果想要弹窗一直保持在屏幕上,则将duration: null即可
        duration: Duration(seconds: seconds),
        backButtonBehavior: backButtonBehavior,
        align: Alignment(0, -1.05),
        toastBuilder: (cancel) {
          return CustomTopWidget(
            cancelFunc: cancel,
          );
        },
        enableSlideOff: enableSlideOff,
        onlyOne: onlyOne,
        crossPage: crossPage);
  }

  ///获取app信息
  getAppPackageInfo() {
    // PackageInfo.fromPlatform().then((PackageInfo packageInfo) {
    //   String appName = packageInfo.appName;
    //   String packageName = packageInfo.packageName;
    //   String version = packageInfo.version;
    //   String buildNumber = packageInfo.buildNumber;
    //   logger.d('appName${appName}, packageName${packageName}, version${version}, buildNumber${buildNumber}');
    // });
  }


  @override
  Widget build(BuildContext context) {
    Loading.ctx = context; // 注入context
    return WillPopScope(
      onWillPop: () async {
        // 点击返回键的操作
        if (lastPopTime == null ||
            DateTime.now().difference(lastPopTime) > Duration(seconds: 2)) {
          lastPopTime = DateTime.now();
          BotToast.showText(text: '再按一次退出');
        } else {
          lastPopTime = DateTime.now();
          // 退出app
          await SystemChannels.platform.invokeMethod('SystemNavigator.pop');
        }
      },
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        key: _bottomSheetKey,
        body: IndexedStack(
          index: _selectedIndex,
          children: _bottomNavPages,
        ),
        bottomNavigationBar: _widgetBootom()
      )
    );
  }

  Widget _widgetBootom(){
    return BottomAppBar(
      color: Theme.of(context).bottomAppBarColor,
      child: Container(
        height: ScreenUtil().getHeightPx(CommonHeight.bootomappBarHeight),
        child: Row(
          children: _listWidget(),
          mainAxisAlignment: MainAxisAlignment.spaceAround,
        ),
      ),
    );
  }

  List<Widget> _listWidget(){
    List<Widget> _list = [];
    for (var i = 0; i < _footerText.length; i++) {
      Widget _addWidget = Expanded(
        child: InkResponse(
          highlightColor: Colors.transparent,
          radius: 0.0,
          onTap: (){
            setState(() {
              _selectedIndex = i;
            });
          },
          child: Container(
            padding: EdgeInsets.only(top: ScreenUtil().getWidthPx(10)),
            child: Column(
              children: <Widget>[
                Icon(IconData(_footerText[i]['icon'], fontFamily: Constants.IconFontFamily),color: Color(_selectedIndex == i ? _selectColor : _noColor), size: ScreenUtil().getSp(_iconSize)),
                SizedBox(height: 1,),
                Center(
                  child: Cptext(text: _footerText[i]['text'],style: TextStyle(color: Color(_selectedIndex == i ? _selectColor : _noColor), fontSize: 11),),
                ),
              ],
            ),
          ),
        )
      );
      _list.add(_addWidget);
    }
    return _list;
  }
}